package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.activity.viewModels
import com.google.gson.Gson
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.AmibaSysUserAdminBean
import com.hinnotek.amoeba.bean.old.AmountAllocatedBean
import com.hinnotek.amoeba.bean.old.CompanyPhoneJson
import com.hinnotek.amoeba.bean.old.PhoneNum
import com.hinnotek.amoeba.databinding.ActivityPhoneNumberPaymentAddBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.utilities.ClickUtil
import com.lee.common.utils.SharedPreUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.viewmodels.ManageViewModel
import com.hinnotek.amoeba.viewmodels.PhoneViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

@AndroidEntryPoint
class PhoneNumberPaymentAddActivity : BaseActivity<ActivityPhoneNumberPaymentAddBinding>() {

    private var orgId = 0
    private var approvalUserId = 0

    private val viewModel by viewModels<PublicInterfaceViewModel>()
    private val manageViewModel by viewModels<ManageViewModel>()
    private val phoneViewModel by viewModels<PhoneViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("添加手机号缴费申请")

        setContentView(R.layout.activity_phone_number_payment_add)
    }

    override fun initVew() {


        bindingView.rbPnpAddPhone.setOnClickListener {
            val viewPnp: View = LayoutInflater.from(mContext)
                .inflate(R.layout.include_pnp_detail_layout, bindingView.llPnpDetails, false)
            bindingView.llPnpDetails.addView(viewPnp)
            viewPnp.findViewById<View>(R.id.tv_del)
                .setOnClickListener { v1: View? -> bindingView.llPnpDetails.removeView(viewPnp) }
        }
        bindingView.superButtonSubmit.setOnClickListener(View.OnClickListener {
            if (ClickUtil.isFastClick()) {
                return@OnClickListener
            }
            val companyPhoneJson = CompanyPhoneJson()
            val orgName = bindingView.escPnpChooseAmoeba.editText.text.trim()
            if (StringUtils.isEmpty(orgName)) {
                ToastUtils.show(mContext, "请选择阿米巴")
                return@OnClickListener
            }

            val phoneNum = bindingView.etPnpNumber.text.trim()
            if (StringUtils.isEmpty(phoneNum)) {
                ToastUtils.show(mContext, "请填写缴费号码")
                return@OnClickListener
            }
            companyPhoneJson.companyPhones.add(PhoneNum(phoneNum.toString()))
            for (i in 0 until bindingView.llPnpDetails.childCount) {
                bindingView.llPnpDetails.getChildAt(i)
                val etPnpNumberSV = bindingView.etPnpNumber.text.trim()
                if (StringUtils.isEmpty(etPnpNumberSV)) {
                    ToastUtils.show(mContext, "请填写缴费号码")
                    return@OnClickListener
                }
                companyPhoneJson.companyPhones.add(PhoneNum(etPnpNumberSV.toString()))
            }

            val etPnpTotalS = bindingView.etPnpTotal.text.trim()
            if (StringUtils.isEmpty(etPnpTotalS)) {
                ToastUtils.show(mContext, "请填写缴费金额合计")
                return@OnClickListener
            }
            val approvalUser =
                bindingView.escPnpRelatedApprover.editText.text.trim()
            if (StringUtils.isEmpty(approvalUser)) {
                ToastUtils.show(mContext, "请选择关联审批人")
                return@OnClickListener
            }
            val phonejsonS = Gson().toJson(companyPhoneJson)
            addCompanyPhonePay(
                orgId,
                orgName.toString(),
                etPnpTotalS.toString(),
                approvalUserId,
                approvalUser.toString(),
                2,
                "宁创",
                phonejsonS
            )
        })
    }

    override fun setData() {

        getSysOrgAmibaList()
        viewModel.getCompanySysUserAdmin()
            .observe(this, object : ObserverState<MutableList<AmibaSysUserAdminBean>>() {
                override fun onDataChange(data: MutableList<AmibaSysUserAdminBean>) {
                    val strings = arrayOfNulls<String>(data.size).apply {
                        for (index in data.indices) {
                            this[index] = data[index].personName
                        }
                    }
                    bindingView.escPnpRelatedApprover.initAdapter(strings)
                    bindingView.escPnpRelatedApprover.setOnItemClickListener { _, view, position, id ->
                        approvalUserId = data[position].userId
                    }
                    super.onDataChange(data)
                }
            })

    }

    /**
     * app端添加临时缴费续费申请接口
     */
    private fun addCompanyPhonePay(
        orgId: Int, orgName: String,
        payMoney: String, approvalUserId: Int,
        approvalUser: String, sendUserId: Int, sendUser: String, companyPhoneJson: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        val map = mutableMapOf<String, Any>().apply {
            put("applyUserId", SharedPreUtils.getInteger("userId", 0))
            put("orgId", orgId)
            put("orgName", orgName)
            put("payMoney", payMoney)
            put("approvalUserId", approvalUserId)
            put("approvalUser", approvalUser)
            put("sendUserId", sendUserId)
            put("sendUser", sendUser)
            put("createUser", SharedPreUtils.getString("personName"))
            put("companyPhoneJson", companyPhoneJson)
        }
        phoneViewModel.addCompanyPhonePay(getRequestBody(map)).observe(this,object : ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {
                customDialog.dismiss()
                finishActivity()
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
    }

    /**
     * app端获取全部阿米巴组织接口
     */
    private fun getSysOrgAmibaList() {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        manageViewModel.getSysOrgAmibaList()
            .observe(this, object : ObserverState<MutableList<AmountAllocatedBean>>() {
                override fun onDataChange(data: MutableList<AmountAllocatedBean>) {
                    val amountAllocatedTypeList: MutableList<String?> = ArrayList()
                    for (index in data) {
                        amountAllocatedTypeList.add(index.orgName)
                    }
                    val strings = arrayOfNulls<String>(amountAllocatedTypeList.size)
                    bindingView.escPnpChooseAmoeba.initAdapter(strings)
                    bindingView.escPnpChooseAmoeba.setOnItemClickListener { parent, view, position, id ->
                        orgId = data[position].orgId
                    }
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })

    }
}